package cn.remex.configuration.spring;

import cn.remex.core.util.JsonHelper;
import cn.remex.core.util.Judgment;

import java.beans.PropertyEditorSupport;
import java.util.HashMap;
import java.util.Map;

/**
 * Disc:
 * Created by xinxinran on 2017/8/3.
 */
public class Json2MapEditor extends PropertyEditorSupport {

    /**
     * Gets the property value as a string suitable for presentation
     * to a human to edit.
     *
     * @return The property value as a string suitable for presentation
     * to a human to edit.
     * <p>   Returns null if the value can't be expressed as a string.
     * <p>   If a non-null value is returned, then the PropertyEditor should
     * be prepared to parse that string back in setAsText().
     */
    @Override
    public String getAsText() {
        Map targetMap = (Map) getValue();
        return JsonHelper.toJsonString(targetMap);
    }

    /**
     * Sets the property value by parsing a given String.  May raise
     * java.lang.IllegalArgumentException if either the String is
     * badly formatted or if this kind of property can't be expressed
     * as text.
     *
     * @param text The string to be parsed.
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if(Judgment.nullOrBlank(text)){
            setValue(new HashMap<>());
        }else{
            try{
                setValue(JsonHelper.toJavaObject(text, HashMap.class));
            }catch(Exception e){
                throw new IllegalArgumentException(text, e);
            }
        }
    }
}
